package com.len.service;

import com.github.pagehelper.Page;
import com.len.base.CurrentUser;
import com.len.constant.RedisLockConstant;
import com.len.controller.req.BillRecordReq;
import com.len.core.shiro.ShiroUtil;
import com.len.entity.BillRecordEntity;
import com.len.template.RedisLockTemplate;
import com.len.util.DateUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

@Service
public class BillRecordService {

    @Resource
    private MongoTemplate mongoTemplate;

    @Resource
    private RedisLockTemplate redisLockTemplate;

    @Resource
    private PageService pageService;

    public Page<BillRecordEntity> getList(BillRecordReq req, Page<BillRecordEntity> page){
        Query query = new Query();
        query.skip((page.getPageNum()-1)*page.getPageSize());
        query.limit(page.getPageSize());

        Criteria criteria = new Criteria();
        if (StringUtils.isNotBlank(req.getBeginTime())&&StringUtils.isNotBlank(req.getEndTime())){
            criteria.andOperator(Criteria.where("createTime").gte(Integer.valueOf(DateUtil.date2TimeStamp(req.getBeginTime(),"yyyy-MM-dd")))
                    ,Criteria.where("createTime").lt(Integer.valueOf(DateUtil.date2TimeStamp(req.getEndTime(),"yyyy-MM-dd"))+24*3600));
        }else if (StringUtils.isNotBlank(req.getBeginTime())){
            criteria.and("createTime").gte(Integer.valueOf(DateUtil.date2TimeStamp(req.getBeginTime(),"yyyy-MM-dd")));
        }else if (StringUtils.isNotBlank(req.getEndTime())){
            criteria.and("createTime").lt(Integer.valueOf(DateUtil.date2TimeStamp(req.getEndTime(),"yyyy-MM-dd"))+24*3600);
        }
        query.addCriteria(criteria);
        query.with(Sort.by(
                Sort.Order.desc("createTime")
        ));
        List<BillRecordEntity> list = mongoTemplate.find(query, BillRecordEntity.class);
        list.forEach(recordEntity -> {
            recordEntity.setAmountStr(new BigDecimal(recordEntity.getAmount()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString()+"元");
            recordEntity.setChangeAmountStr(new BigDecimal(recordEntity.getChangeAmount()).divide(new BigDecimal(100),2,BigDecimal.ROUND_HALF_UP).toString()+"元");
        });
        long total = pageService.count(query, BillRecordEntity.class);

        page.addAll(list);
        page.setTotal(total);
        return page;
    }

    public void add(BillRecordReq req) throws Exception {

        CurrentUser currentUser = ShiroUtil.getCurrentUse();
        redisLockTemplate.call(RedisLockConstant.BILL_RECORD,()->{
            Query query = new Query();
            query.with(Sort.by(
                    Sort.Order.desc("createTime")
            ));
            List<BillRecordEntity> list = mongoTemplate.find(query,BillRecordEntity.class);
            BillRecordEntity entity;
            if (list.size() == 0){
                entity = new BillRecordEntity();
                entity.setDes("初始化");
                entity.setAmount(0L);
                entity.setChangeAmount(0L);
                entity.setOperationId(currentUser.getId());
                mongoTemplate.insert(entity);
            }else {
                entity = list.get(0);
            }

            BillRecordEntity entity1 = new BillRecordEntity();
            entity1.setChangeAmount(new BigDecimal(req.getChangeAmount()).multiply(new BigDecimal(100)).setScale(0,BigDecimal.ROUND_HALF_UP).longValue());
            entity1.setAmount(entity.getAmount()+entity1.getChangeAmount());
            entity1.setDes(req.getDes());
            entity1.setOperationId(currentUser.getId());
            mongoTemplate.insert(entity1);
            return null;
        });


    }

}
